package com.demo.user.impl;

import com.demo.api.user.domain.TestUser;
import com.demo.api.user.service.LimitService;
import com.demo.api.user.service.UserService;
import com.demo.common.enums.ResultCode;
import com.demo.common.response.Result;
import com.demo.user.domain.TestLog;
import com.demo.user.mapper.TestLogDao;
import com.demo.user.mapper.TestUserDao;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author luogq
 */
@Service(version = "1.0.0", interfaceClass = UserService.class, timeout = 120000, retries = 3)
@Slf4j
@Component
public class UserServiceImpl implements UserService {

  @Autowired
  private TestUserDao testUserDao;

  @Autowired
  private TestLogDao testLogDao;

  @Reference(version = "1.0.0", check = false)
  private LimitService limitService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Result addUser(TestUser testUser) {
    log.info("分布式事务, xid:{}", RootContext.getXID());
    log.info("新增Test_User, {}", testUserDao);
    try {
      testUserDao.insert(testUser);
      TestLog testLog = new TestLog();
      testLog.setId(ThreadLocalRandom.current().nextLong(1, 500000));
      testLog.setLogDetail("addUser " + testUser.toString());
      testLog.setDt(new Date());
      testLogDao.insert(testLog);
      log.info("新增Test_User正常结束");
      return Result.suc(true);
    } catch (Exception e) {
      log.error("{}", e);
      return Result.fail(ResultCode.SYSTEM_ERROR);
    }
  }

}


